package com.example.springboot.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;




@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/add")
    public Result add(@RequestBody User user){
        try{
            userService.save(user);
        }catch(Exception e){
            return Result.error("插入数据错误");
        }
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user){
        try{
            userService.updateById(user);
        }catch(Exception e){
            return Result.error("更新数据错误");
        }
        return Result.success();
    }

    @DeleteMapping("/delete/{count}")
    public Result delete(@PathVariable String count){
        User currentUser = TokenUtils.getCurrentUser();
        if (count.equals(currentUser.getCount())) {
            throw new ServiceException("不能删除当前的用户");
        }

        try{
            userService.removeById(count);
        }catch(Exception e){
            return Result.error("删除数据错误");
        }
        return Result.success();
    }

    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<String> counts) {
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser!=null&&currentUser.getCount()!=null&&counts.contains(currentUser.getCount())) {
            throw new ServiceException("不能删除当前的用户");
        }

        userService.removeBatchByIds(counts);
        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        List<User> userList=userService.list();
        return Result.success(userList);
    }
    
    @GetMapping("/selectByCount/{count}")
    public Result selectByCount(@PathVariable String count){
        User user=userService.getById(count);
        return Result.success(user);
    }

    @GetMapping("/selectByName/{name}")
    public Result selectByName(@PathVariable String name){
        List<User> userList1=userService.selectByName(name);
        return Result.success(userList1);
    }

    @GetMapping("/selectByRole/{role}")
    public Result selectByRole(@PathVariable String role){
        List<User> userList2=userService.selectByRole(role);
        return Result.success(userList2);
    }
    
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                            @RequestParam String count,
                            @RequestParam String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.like(StrUtil.isNotBlank(count), "count", count);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.eq("role", "顾客");
        // select * from user where count like '%#{count}%' and name like '%#{name}%'
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
    @GetMapping("/selectByPage1")
    public Result selectByPage1(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                            @RequestParam String count,
                            @RequestParam String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.like(StrUtil.isNotBlank(count), "count", count);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.eq("role", "店员");
        // select * from user where count like '%#{count}%' and name like '%#{name}%'
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
    @GetMapping("/selectByPage2")
    public Result selectByPage2(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                            @RequestParam String count,
                            @RequestParam String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.like(StrUtil.isNotBlank(count), "count", count);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.eq("role", "顾客");
        queryWrapper.eq("vip", "是");
        // select * from user where count like '%#{count}%' and name like '%#{name}%'
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String count,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String counts,
                           HttpServletResponse response) throws IOException{
        ExcelWriter writer =ExcelUtil.getWriter(true);
        List<User> list;
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        if(StrUtil.isNotBlank(counts)){
            List<String> countsArr=Arrays.stream(counts.split(",")).collect(Collectors.toList());
            queryWrapper.in("count",countsArr);
        }else{
            //第一种全部导出或者条件导出
            queryWrapper.like(StrUtil.isNotBlank(count), "count", count);
            queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
            queryWrapper.eq("role", "顾客");
        }
        list=userService.list(queryWrapper);
        writer.write(list,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("顾客信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream=response.getOutputStream();
        writer.flush(outputStream,true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }
    @GetMapping("/export1")
    public void exportData1(@RequestParam(required = false) String count,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String counts,
                           HttpServletResponse response) throws IOException{
        ExcelWriter writer =ExcelUtil.getWriter(true);
        List<User> list;
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        if(StrUtil.isNotBlank(counts)){
            List<String> countsArr=Arrays.stream(counts.split(",")).collect(Collectors.toList());
            queryWrapper.in("count",countsArr);
        }else{
            //第一种全部导出或者条件导出
            queryWrapper.like(StrUtil.isNotBlank(count), "count", count);
            queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
            queryWrapper.eq("role", "店员");
        }
        list=userService.list(queryWrapper);
        writer.write(list,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("店员信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream=response.getOutputStream();
        writer.flush(outputStream,true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }
    @GetMapping("/export2")
    public void exportData2(@RequestParam(required = false) String count,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String counts,
                           HttpServletResponse response) throws IOException{
        ExcelWriter writer =ExcelUtil.getWriter(true);
        List<User> list;
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        if(StrUtil.isNotBlank(counts)){
            List<String> countsArr=Arrays.stream(counts.split(",")).collect(Collectors.toList());
            queryWrapper.in("count",countsArr);
        }else{
            //第一种全部导出或者条件导出
            queryWrapper.like(StrUtil.isNotBlank(count), "count", count);
            queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
            queryWrapper.eq("role", "顾客");
            queryWrapper.eq("vip", "是");
        }
        list=userService.list(queryWrapper);
        writer.write(list,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("会员信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream=response.getOutputStream();
        writer.flush(outputStream,true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<User> userList = reader.readAll(User.class);
        // 写入数据到数据库
        try {
            userService.saveBatch(userList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("数据批量导入错误");
        }
        return Result.success();
    }
}
